package controllers

import (
	"books1/cache"
	"books1/models"
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
)

type BookController struct {
	beego.Controller
}

func (c *BookController) Create() {
	var err error
	bookId, _ := c.GetInt("book_id")
	title := c.GetString("title")
	name := c.GetString("name")
	man := c.GetString("man")
	look := c.GetString("look")
	classify := c.GetString("classify")
	time := c.GetString("time")

	var books models.Books
	books.BooksId = bookId
	books.Title = title
	books.Name = name
	books.Man = man
	books.Look = look
	books.Classify = classify
	books.Time = time

	if bookId == 0 || title == "" || name == "" || man == "" || look == "" || classify == "" || time == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "数据不能为空",
		}
		c.ServeJSON()
		return
	}

	if err = books.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "系统错误",
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("books_id_%d", books.ID)
	jsonData, _ := json.Marshal(&books)
	cache.Rdb.Set(cache.Ctx, key, jsonData, 0)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}
func (c *BookController) List() {

	var err error
	var book []models.Books
	err = models.DB.Find(&book).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "查询失败",
			"data": nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "查询成功",
			"data": book,
		}
		c.ServeJSON()
		return
	}

}
func (c *BookController) Update() {
	var err error
	id, _ := c.GetInt("id")
	bookId, _ := c.GetInt("book_id")
	title := c.GetString("title")
	name := c.GetString("name")
	man := c.GetString("man")
	look := c.GetString("look")
	classify := c.GetString("classify")
	time := c.GetString("time")

	var books models.Books
	books.ID = uint(id)
	books.BooksId = bookId
	books.Title = title
	books.Name = name
	books.Man = man
	books.Look = look
	books.Classify = classify
	books.Time = time

	if bookId == 0 || title == "" || name == "" || man == "" || look == "" || classify == "" || time == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "数据不能为空",
		}
		c.ServeJSON()
		return
	}

	if err = books.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "系统错误",
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("books_id_update_%d", books.ID)
	jsonData, _ := json.Marshal(&books)
	cache.Rdb.Set(cache.Ctx, key, jsonData, 0)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "修改成功",
	}
	c.ServeJSON()
	return
}
func (c *BookController) Del() {

	id, _ := c.GetInt("id")
	var book models.Books
	book.ID = uint(id)

	key := fmt.Sprintf("book_id_del", book.ID)
	cache.Rdb.Del(cache.Ctx, key)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return

}
